/**
 * 
 */
package com.nassir.test;

import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.RAMDirectory;

/**
 * 搜索测试
 * @author Winter Lau
 * @date 2010-10-18 下午09:20:18
 */
public class SearchTester {
	
	private static RAMDirectory dir;
	private static SimpleAnalyzer a;
	private static IndexSearcher searcher;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		buildIndex();
		testSearch();
	}

	static void testSearch() throws Exception {
		Query q = new TermQuery(new Term("tags","TkRoot".toLowerCase()));
		TopDocs docs = searcher.search(q, null, 100000);
		System.out.println("HITS:"+docs.totalHits);
		for(int i = 0; i< docs.totalHits;i++){
			ScoreDoc s_doc = docs.scoreDocs[i];
			Document doc = searcher.doc(s_doc.doc);
			System.out.println(doc);
		}
	}
	
	static void buildIndex() throws Exception {
		dir = new RAMDirectory();
		a = new SimpleAnalyzer();
		IndexWriter writer = new IndexWriter(dir, a, IndexWriter.MaxFieldLength.UNLIMITED);
		Document doc = new Document();
		doc.add(new Field("id", "1", Field.Store.YES, Field.Index.NOT_ANALYZED));
		doc.add(new Field("tags", "Java,数组,TkRoot", Field.Store.NO, Field.Index.ANALYZED));
		System.out.println(doc);
		writer.addDocument(doc);
		writer.close();
		searcher = new IndexSearcher(dir);
	}
}

